package com.shengwei.truck.driver.vm;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.annotation.NonNull;
import com.shengwei.truck.driver.model.DataSource;
import com.shengwei.truck.driver.model.Repository;
import com.shengwei.truck.driver.view.ui.app.MyApplication;
import com.shengwei.truck.driver.vm.BaseViewModel;
import com.shengwei.truck.driver.vm.LoginViewModel;

/**
 这个工厂用来 生成ViewModel（VM层的实例）
 其中Repository+DataSource共同构成了M层。
 */
public class ViewModelFactory implements ViewModelProvider.Factory {
    MyApplication mApp;

    public ViewModelFactory(MyApplication app) {
        mApp = app;
    }

    public ViewModelFactory() {
    }
    /**
     *生成各页面的ViewModel实例
     * @param modelClass:各页面的ViewModel类的class类型
     * @param <T> 类泛型
     * @return ViewModel
     */
    @NonNull
    @Override
    @SuppressWarnings("unchecked")
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if (modelClass.isAssignableFrom(LoginViewModel.class)) {
            //生成VM层实例，其中Repository+DataSource共同构成了M层。
            return (T) new LoginViewModel(mApp, Repository.getInstance(DataSource.getSingleInstance()));
        }
        else {
            return (T) new BaseViewModel();
        }
    }
}